package cn.edu.ujn.finalwork.c;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.edu.ujn.finalwork.dao.Base;
import cn.edu.ujn.finalwork.dao.User;
import cn.edu.ujn.finalwork.dao.UserMapper;
import cn.edu.ujn.finalwork.service.IBaseService;
import cn.edu.ujn.finalwork.service.IUserService;
import cn.edu.ujn.finalwork.util.MD5Encoder;

@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IBaseService baseService;

    private int id=0;

    @PostMapping("/login")
    public String success(HttpServletRequest request,HttpSession session,@RequestParam("code") String code, @RequestParam("password") String password, Model model) {
        HttpSession session1 = request.getSession();
        session1.setAttribute("USER_SESSION", code);
        String salt="123456";
        String result = null;
        MD5Encoder pe = new MD5Encoder();
        try {
            result = pe.geMd5(salt, password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        

        User selectByCode = userService.selectByCode(code);
        if(selectByCode==null )
        {
            model.addAttribute("fail","该用户不存在！");
            return "failure";
        }
        else if (selectByCode.getUserPassword().equals(result)) {

            
            id=selectByCode.getUserId();
            User user0 = new User();
            user0.setUserId(id);
            user0.setUserState("1");
            userService.updateByPrimaryKeySelective(user0);
            selectByCode=userService.selectByCode(code);
            id = selectByCode.getUserId();
            Base base = new Base();
            base.setDictTypeCode(selectByCode.getGender());
            base.setDictTypeName("性别");
            Base base2 = baseService.selectByType_CodeAndType_Name(base);
            session.setAttribute("sex", base2.getDictItemName());
            model.addAttribute("sex", base2.getDictItemName());
            base.setDictTypeCode(selectByCode.getUserAuthority());
            base.setDictTypeName("用户权限");
            Base base3 = baseService.selectByType_CodeAndType_Name(base);
            session.setAttribute("authority",base3.getDictItemName());
            model.addAttribute("authority", base3.getDictItemName());
            base.setDictTypeCode(selectByCode.getUserState());
            base.setDictTypeName("用户状态");
            Base base4 = baseService.selectByType_CodeAndType_Name(base);
            session.setAttribute("status",base4.getDictItemName() );
            model.addAttribute("status", base4.getDictItemName());
            // 获取日期
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(sdf.format(date));
            User user = new User();
            user.setUserId(selectByCode.getUserId());
            user.setLogData(date);
            // 获取ip地址
            ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            String localAddr = request.getLocalAddr();
            int serverPort = request.getServerPort();
            String ip = "http://" + localAddr + ":" + serverPort;
            user.setLoginIp(ip);
            userService.updateByPrimaryKeySelective(user);
            User user1 = userService.selectByCode(code);
            model.addAttribute("user", user1);
            session.setAttribute("userr",user1 );
            if (user1.getUserAuthority().equals("1")) {
                return "shouyeG";
            } else {
                return "shouye";
            }
        }
        // }
        else {
            model.addAttribute("fail","密码错误！");
            return "failure";
        }

    }
    @GetMapping("/returnS")
    public String fanhuiS(HttpSession session) {
        User a = (User)session.getAttribute("userr");
        if(a.getUserAuthority().equals("1")){
             return "shouyeG";
        }else {
            return "shouye";
        }
       
    }
    @GetMapping("/test")
    public String test() {
        return "login";
    }

    @GetMapping("/tui")
    public String t() {
        return "quit";
    }
    @GetMapping("tuichu")
    public String person(HttpSession session) {
        User user = new User();
        user.setUserId(id);
        user.setUserState("0");
        userService.updateByPrimaryKeySelective(user);
        User key = userService.selectByPrimaryKey(id);
        session.setAttribute("userr", key);
        session.setAttribute("USER_SESSION",null);
        return "login";
    }
    @GetMapping("/geren")
    public String p(Model model) {
        User user1 = userService.selectByPrimaryKey(id);
        model.addAttribute("user", user1);
        Base base=new Base();
        base.setDictTypeName("性别");
        base.setDictTypeCode(user1.getGender());
        Base base2 = baseService.selectByType_CodeAndType_Name(base);
        model.addAttribute("sex", base2.getDictItemName());
        return "person";
    }
    @PostMapping("/xiugai")
    public String xiugai(Model model) {
        User user1 = userService.selectByPrimaryKey(id);
        model.addAttribute("user", user1);
        Base base=new Base();
        base.setDictTypeName("性别");
        base.setDictTypeCode(user1.getGender());
        Base base2 = baseService.selectByType_CodeAndType_Name(base);
        model.addAttribute("sex", base2.getDictItemName());
        if(user1.getGender().equals("1"))
        {
            model.addAttribute("girl", "checked");
            model.addAttribute("boy", "");
        }else {
            model.addAttribute("boy", "checked");
            model.addAttribute("girl", "");
        }
        
        return "revise";
    }
    @PostMapping("/baocun")
    public String baocun(HttpSession session,@RequestParam("name") String name, @RequestParam("sex") String sex, Model model) {
        User user=new User();
        user.setUserId(id);
        user.setUserName(name);
        user.setGender(sex);
        userService.updateByPrimaryKeySelective(user);
        User user2 = userService.selectByPrimaryKey(id);
        model.addAttribute("user", user2);
        Base base=new Base();
        base.setDictTypeName("性别");
        base.setDictTypeCode(user.getGender());
        Base base2 = baseService.selectByType_CodeAndType_Name(base);
        model.addAttribute("sex", base2.getDictItemName());
        session.setAttribute("userr", user2);
        return "person";
    }
    @GetMapping("/zhuxiao")
    public String zhuxiao() {
        return "delete";
    }
    @GetMapping("/shan")
    public String shan(Model model,HttpSession session) {
        
        if(id==0)
        {
            model.addAttribute("fail","该用户未登录！不能进行相关操作！");
            return "failure";
        }else {
        User user = userService.selectByPrimaryKey(id);
        userService.delectByPrimaryKey(id);
        session.setAttribute("USER_SESSION",null);
        return "login";
        }
       
    }
    @GetMapping("/zhuce")
    public String zhuce(HttpSession session) {
        String i="不是空啊！";
        session.setAttribute("USER_SESSION",i);
        return "register";
    }
    @GetMapping("/ce")
    public String ce(HttpSession session) {
        session.setAttribute("USER_SESSION",null);
        return "login";
    }

    @PostMapping("/zhu")
    public String zhu(HttpSession session,@RequestParam("name") String name, @RequestParam("password") String password, @RequestParam("password1") String password1,Model model) {
        if(password.equals(password1))
        {
            String code="";
            for(int i=0;i<10;i++) {
                int r=(int)(Math.random()*10);
               code=code+r;
            }
            System.out.println(code);
            User user=new User();
            user.setUserCode(code);
            user.setGender("1");
            user.setUserName(name);
            user.setUserState("0");
            user.setUserPassword(password1);
            user.setUserAuthority("2");
            user.setUserAvatar("https://img2.baidu.com/it/u=1990393179,676469763&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500");
            userService.insertSelective(user);
            model.addAttribute("code",code);
            
            return "success"; 
        }else
        {
            model.addAttribute("fail","两次输入密码不一致！");
            return "failure";
        }
        
    }
   
}




